import currency from "./currencyTime.js"
import methods from "./methods.js";
import store from "../pages/store/index.js"

// 是否登录
export function isLogin() {
	const token = uni.getStorageSync('token');
	if (!token) {
		uni.navigateTo({
			url: '/pages/login/index'
		})
		return false
	} else {
		return true
	}
}

export function xoIsShare() {
	if (store.state.xoIsShare == 'true') {
		uni.showToast({
			icon: 'none',
			title: '抱歉，分享账号不能使用该功能'
		})
		return false
	} else {
		return true
	}
}



export default {
	//登录成功
	loginSuc(token,user,pass){
		if(token){
			uni.setStorageSync('token', token)
		}
		if(user){
			uni.setStorageSync('phone', user)
		}
		if(pass){
			uni.setStorageSync('pass', pass)
		}
		//打开ws
		if (!store.state.isOpen) {
			store.dispatch('link')
		}
		this.getcid()
		//打开签到定时器
		//store.dispatch('time')
	},
	//退出登录
	initialValue() {
		console.log('删除')
		//清除签到定时器
		// clearInterval(this.$store.state.IntervalTimeObj);
		// this.$store.state.IntervalTimeObj = null
		
		//删除信息
		uni.removeStorageSync('token')
		uni.removeStorageSync('userInfo')
		store.state.userInfo = ''
		//关闭ws心跳
		if(store.state.interval){
			clearInterval(store.state.interval)
		}
		uni.closeSocket();

		//退出苹果登录
		//main.iphoneOut()
		//退出涂鸦
		// tuyaModule.logout(result => {
		// 	if (result.state == 1) {} else {}
		// })
	},
	//修改配置
	setConfigFun(id, val) {
		console.log('id:', id)
		let obj = {}

		switch (id) {
			case 0:
				//路程
				obj.distance = val
				break;
			case 1:
				//时长
				obj.duration = val
				break;
			case 2:
				//热量
				obj.heat = val
				break;
			case 4:
				//运动类型
				obj.sports = val
			case 5:
				//每日目标步数
				obj.step = val
				break;
			case 6:
				//语音播报
				obj.voiceOpen = val.voiceOpen
				obj.voiceDistanceOpen = val.voiceDistanceOpen
				obj.voiceDurationOpen = val.voiceDurationOpen
				obj.voiceSpeedOpen = val.voiceSpeedOpen
				break;
			case 7:
				//语音播报
				obj.voiceDistanceOpen = val
				break;
			case 8:
				//语音播报
				obj.voiceDurationOpen = val
				break;
			case 9:
				//语音播报
				obj.voiceSpeedOpen = val
				break;
			case 10:
				//播放频率
				obj.frequencyType = val.frequencyType
				obj.frequency = val.frequency
				break;

		}

		return methods.setConfig(obj).then(res => {
			if (res.data.code == 200) {
				switch (id) {
					case 0:
						//路程
						store.state.configObj.distance = val
						break;
					case 1:
						//时长
						store.state.configObj.duration = val
						break;
					case 2:
						//热量
						store.state.configObj.heat = val
						break;
					case 4:
						//运动类型
						store.state.configObj.sports = val
					case 5:
						//每日目标步数
						store.state.configObj.step = val
						break;
					case 6:
						//语音播报
						store.state.configObj.voiceOpen = val.voiceOpen
						store.state.configObj.voiceDistanceOpen = val.voiceDistanceOpen
						store.state.configObj.voiceDurationOpen = val.voiceDurationOpen
						store.state.configObj.voiceSpeedOpen = val.voiceSpeedOpen
						break;
					case 7:
						//语音播报
						store.state.configObj.voiceDistanceOpen = val
						break;
					case 8:
						//语音播报
						store.state.configObj.voiceDurationOpen = val
						break;
					case 9:
						//语音播报
						store.state.configObj.voiceSpeedOpen = val
						break;
					case 10:
						//播放频率
						store.state.configObj.frequencyType = val.frequencyType
						store.state.configObj.frequency = val.frequency
						break;
				}

				store.state.isSxSports = true
				return true
			}
		}).catch(err => {
			uni.showToast({
				icon: 'none',
				title: err.data.message
			})
		})
	},
	//微信支付
	weixiPay(payType, payCount) {
		let self = this
		let obj = {
			type: payType,
			count: payCount || ''
		}
		return methods.vip2Buy(obj).then(res => {
			if (res.data.code == 200) {
				if (res.data.data) {
					//订单对象，从服务器获取
					var orderInfo = {
						"appid": "wxbb4407dc30cfeccc", // 应用ID（AppID）
						"partnerid": "1655556489", // 商户号（PartnerID）
						"prepayid": res.data.data.prepayId, // 预支付交易会话ID
						"package": "Sign=WXPay", // 固定值
						"noncestr": res.data.data.noncestr, // 随机字符串
						"timestamp": res.data.data.timestamp, // 时间戳（单位：秒）
						"sign": res.data.data.sign // 签名，这里用的 MD5 签名
					};

					uni.getProvider({
						service: 'payment',
						success: function(res) {
							if (~res.provider.indexOf('wxpay')) {
								uni.requestPayment({
									"provider": "wxpay", //固定值为"wxpay"
									"orderInfo": orderInfo,
									success: function(res) {
										store.state.isPaySuccess = true
										uni.showToast({
											icon: 'none',
											title: store.state.country ==
												'zh-Hans' ? '成功' : 'success'
										})
									},
									fail: function(err) {
										uni.showToast({
											icon: 'none',
											title: store.state.country ==
												'zh-Hans' ? '失败' : 'fail'
										})
									}
								});
							}
						}
					});

				}
			} else {
				uni.showToast({
					icon: 'none',
					title: res.data.message
				})
			}

			return true
		}).catch(err => {
			uni.showToast({
				icon: 'none',
				title: err.data.message
			})
		})
	},
	//支付宝
	alipay(payType, payCount) {
		let self = this
		let obj = {
			type: payType,
			count: payCount || ''
		}
		return methods.createOrderByZfb(obj).then(res => {
			if (res.data.code == 200) {
				if (res.data.data) {
					//订单对象，从服务器获取
					var orderInfo = res.data.data.orderInfo
					uni.getProvider({
						service: 'payment',
						success: function(res) {
							if (~res.provider.indexOf('alipay')) {
								uni.requestPayment({
									"provider": "alipay", //固定值为"wxpay"
									"orderInfo": orderInfo,
									success: function(res) {
										store.state.isPaySuccess = true
										uni.showToast({
											icon: 'none',
											title: store.state.country ==
												'zh-Hans' ? '成功' : 'success'
										})
									},
									fail: function(err) {
										uni.showToast({
											icon: 'none',
											title: store.state.country ==
												'zh-Hans' ? '失败' : 'fail'
										})
									}
								});
							}
						}
					});

				}
			} else {
				uni.showToast({
					icon: 'none',
					title: res.data.message
				})
			}

			return true
		}).catch(err => {
			uni.showToast({
				icon: 'none',
				title: err.data.message
			})
		})
	},
	//paypal
	paypal(payType, payCount) {
		//订单对象，从服务器获取
		let self = this
		let obj = {
			type: payType,
			count: payCount || ''
		}
		methods.vip2CreateOrderByPaypal(obj).then(res => {
			if (res.data.code == 200) {
				if (res.data.data) {
					var orderInfo = {
						"clientId": res.data.data.clientId, //客户端id
						"orderId": res.data.data.orderId, //订单id
						"userAction": "continue", //  paynow/continue
						"currency": res.data.data.currency, // 币种  
						"environment": res.data.data.environment, //运行环境 sandbox/live
					};
					uni.getProvider({
						service: 'payment',
						success: function(res) {
							if (~res.provider.indexOf('paypal')) {
								uni.requestPayment({
									"provider": "paypal",
									"orderInfo": orderInfo,
									success: function(res) {
										var rawdata = JSON.parse(res.rawdata);
										//console.log("orderId：" + rawdata.orderId);
										if (rawdata.orderId) {
											let obj = {
												orderId: rawdata.orderId
											}

											methods.vip2PaypalBuy(obj).then(res => {
												store.state.isPaySuccess = true
												uni.showToast({
													icon: 'none',
													title: store.state
														.country ==
														'zh-Hans' ?
														'成功' : 'success'
												})
											}).catch(err => {
												uni.showToast({
													icon: 'none',
													title: store.state
														.country ==
														'zh-Hans' ?
														'失败' : 'fail'
												})
											})
										}
									},
									fail: function(err) {
										//console.log('fail:' + JSON.stringify(err));
										// uni.showToast({
										// 	icon:'none',
										// 	title:JSON.stringify(err)
										// })
									}
								});
							}
						}
					});

				}
			} else {
				uni.showToast({
					icon: 'none',
					title: res.data.message
				})
			}
		}).catch(err => {
			uni.showToast({
				icon: 'none',
				title: err.data.message
			})
		})

	},
	//手机隐号
	jxPhone(phone) {
		let hiddenPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
		return hiddenPhone
	},
	//格式化数字  
	formatNumber(num) {
		num = Number(num);
		if (num == 0 || (num > 0 && num < 10000)) {
			return num + '';
		} else {
			return (num / 10000).toFixed(1) + 'w';
		}
	},
	// 格式化时间
	parseTime(time, cFormat) {
		return currency.parseTime(time, cFormat);
	},
	// 拼接时间
	parseTime2(time) {
		return time.slice(0, 4) + '-' + time.slice(4, 6) + '-' + time.slice(6, 8) + ' ' + time.slice(8, 10) + ':' + time
			.slice(10, 12)
	},
	// 拼接时间
	parseTime3(time) {
		return time.slice(0, 4) + '-' + time.slice(4, 6) + '-' + time.slice(6, 8)
	},
	// 拼接时间 20231221165754
	parseTime4(time) {
		return time.slice(0, 4) + '-' + time.slice(4, 6) + '-' + time.slice(6, 8) + ' ' + time.slice(8, 10) + ':' + time
			.slice(10, 12)
	},
	iphoneOut() {
		if (store.state.platform == 'ios') {
			plus.oauth.getServices(servies => {
				const provide = servies.reduce((cur, next) => {
					cur.push(next.id);
					return cur;
				}, []);
				const apple = servies[provide.indexOf('apple')];

				apple.logout(res => {}, err => {});
			})

		}
	},
	// 拼接时间 20231221165754
	parseTime5(time) {
		return time.slice(4, 6) + '-' + time.slice(6, 8)
	},
	//获取指定日期所在月的第一天和最后一天 '2023-11-15'
	getMonthStartAndEnd(dateString) {
		const date = dateString ? new Date(dateString) : new Date();
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		// const firstDay = new Date(year, month - 1, 1);
		const lastDay = new Date(year, month, 0);
		const formattedFirstDay = `${year}-${month.toString().padStart(2, '0')}-01`;
		const formattedLastDay = `${year}-${month.toString().padStart(2, '0')}-${lastDay.getDate()}`;
		return {
			firstDay: formattedFirstDay,
			lastDay: formattedLastDay
		};
	},
	isWithinOneMinute(timestamp1, timestamp2) {
		return currency.isWithinTwoMinutes(timestamp1, timestamp2);
	},
	//是否是本周内
	isDy7Day(timestamp) {
		return currency.isDy7Day(timestamp);
	},
	//聊天时间显示
	timeFliter(timestamp) {
		return currency.timeFliter(timestamp);
	},
	//今天昨天
	getDayOrYesterday(timestamp) {
		return currency.getDayOrYesterday(timestamp);
	},
	//周几
	getDayOfWeek(timestamp) {
		return currency.getDayOfWeek(timestamp);
	},
	//秒转时间
	getStoDate(s) {
		const hours = Math.floor(s / 3600);
		const minutes = Math.floor((s % 3600) / 60);
		const remainingSeconds = s % 60;
		return `${hours}:${minutes}:${remainingSeconds}`
	},
	//语音秒转时间
	getStoYyDate(s) {
		const hours = Math.floor(s / 3600);
		const minutes = Math.floor((s % 3600) / 60);
		const remainingSeconds = s % 60;
		return `${hours == 0 ? '' : hours+':'}${minutes == 0 ? '' : minutes + ':'}${remainingSeconds}`
	},
	getcid() {
		// #ifdef APP-PLUS
		const _self = this;
		uni.getPushClientId({
			success: (res) => {
				_self.sendCidFun(res.cid)
			},
			fail(err) {}
		})
		// #endif
	},
	sendCidFun(cid) {
		let obj = {
			cid: cid
		}
		methods.addCid(obj).then(res => {
			if (res.data.code == 200) {

			} else {

			}
		}).catch(err => {

		})
	},
}